﻿/********************************************************
 * Module Name    : show field in single layout
 * Purpose        : define Sysytem Display type to a contant int value 
 *                : the constant is used for different checks through out  proj 
 * Class Used     : -----------
 * Created By     : Harwinder 
 * Date           : 
**********************************************************/
using System;
using System.Collections.Generic;
using System.Text;
//using VAdvantage.Process; using VAdvantage.ProcessEngine;

namespace VAdvantage.Classes
{
#region "Old TabObj"
   //public class TabObj : Evaluatee
   // {
   //     #region "Declaration"

   //     /** Value Object                    */
   //     private TABVO _vo;
   //     private TableObj _gridTable;

   //     private string _keyColumnName = "null";
   //     private string _linkColumnName = "";
   //     private string _extendedWhere;

   //     private MultiMap<string, FieldObj> _depOnField = new MultiMap<string, FieldObj>();

   //     private volatile bool _loadComplete = false;
   //     /** Is Tab Included in other Tab  */
   //     private bool _included = false;

   //     private Query _query = new Query();
   //     private String _oldQuery = "0=9";
   //     private String _linkValue = "999999";

   //     /** Order By Array if SortNo 1..3   */
   //     private string[] _OrderBys = new string[3];
   //     /** List of Key Parents     */
   //     private List<string> _parents = new List<String>(2);

   //     // Attachments
   //     private SortedList<int, int> _attachments = null;

   //     // current row
   //     private int _currentRow = 0;

   //     private DataRowView _rowData = null;

   //     private bool _isCalloutExecute = false;


   //     public bool IsRowDirty
   //     {
   //         get;
   //         set;
   //     }

   //     /** Chats				*/
   //     private SortedList<int, int> _chats = null;

   //     #endregion

   //     public VDataGridView.VDataGridView GridPanal
   //     {
   //         get;
   //         set;
   //     }
   //     public Panel FieldPanal
   //     {
   //         get;
   //         set;
   //     }

   //     /// <summary>
   //     /// Gets and Sets current row of vdatagridview
   //     /// </summary>
   //     public int CurrentRow
   //     {
   //         get
   //         {
   //             //if (GridTable().CurrentRow != null)
   //             //    return GridTable().CurrentRow.Index;
   //             //else
   //             //    return -1;
   //             return _currentRow;
   //         }
   //         set
   //         {
   //             _currentRow = value;
   //         }
   //     }

   //     public DataRowView CurrentRowData
   //     {
   //         get
   //         {
   //             return _rowData;
   //         }
   //         set
   //         {
   //             _rowData = value;
   //         }
   //     }


   //     /// <summary>
   //     /// Standard Constructor
   //     /// </summary>
   //     /// <param name="vo"></param>
   //     /// <param name="curDays"></param>
   //     public TabObj(TABVO vo, int curDays)
   //     {
   //         _vo = vo;
   //         _vo.OnlyCurrentDays = curDays;
   //         _gridTable = new TableObj(_vo.ctx, _vo.AD_TABLE_ID, _vo.TABLENAME, _vo.windowNum, _vo.tabNum, true, this);
   //         _gridTable.SetReadOnly((_vo.ISREADONLY == 'Y') ? true : false || _vo.ISVIEW);
   //         _gridTable.SetDeleteable(_vo.ISDELETEABLE);

   //         IniTab();
   //     }

   //     /// <summary>
   //     ///Initialize Tab with record from AD_Tab_v
   //     /// </summary>
   //     /// <returns></returns>
   //     protected bool IniTab()
   //     {
   //         _extendedWhere = _vo.WHERECLAUSE;

   //         if (!LoadFields())
   //         {
   //             _loadComplete = true;
   //             return false;
   //         }
   //         //order by
   //         _gridTable.SetOrderClause(GetOrderByClause(_vo.OnlyCurrentDays));
   //         _loadComplete = true;
   //         return true;
   //     }

   //     /// <summary>
   //     /// Set Order By Clause
   //     /// </summary>
   //     /// <param name="onlyCurrentDays"></param>
   //     /// <returns></returns>
   //     private string GetOrderByClause(int onlyCurrentDays)
   //     {
   //         //	First Prio: Tab Order By
   //         if (_vo.ORDERBYCLAUSE.Length > 0)
   //             return _vo.ORDERBYCLAUSE;

   //         //	Second Prio: Fields (save it)
   //         _vo.ORDERBYCLAUSE = "";
   //         for (int i = 0; i < 3; i++)
   //         {
   //             string order = _OrderBys[i];
   //             if (order != null && order != "" && order.Length > 0)
   //             {
   //                 if (_vo.ORDERBYCLAUSE.Length > 0)
   //                     _vo.ORDERBYCLAUSE += ",";
   //                 _vo.ORDERBYCLAUSE += order;
   //             }
   //         }
   //         if (_vo.ORDERBYCLAUSE.Length > 0)
   //             return _vo.ORDERBYCLAUSE;

   //         //	Third Prio: onlyCurrentRows
   //         _vo.ORDERBYCLAUSE = "Created";
   //         if (onlyCurrentDays > 0)
   //             _vo.ORDERBYCLAUSE += " DESC";
   //         return _vo.ORDERBYCLAUSE;
   //     }	//	getOrderByClause

   //     /// <summary>
   //     /// Get Field data and add to MTable, if it's required or displayed.
   //     /// </summary>
   //     /// <returns></returns>
   //     protected bool LoadFields()
   //     {
   //         //  Add Fields
   //         for (int f = 0; f < _vo.lstFields.Count; f++)
   //         {
   //             FIELDVO voF = (FIELDVO)_vo.lstFields[f];
   //             //	Add Fields to Table
   //             if (voF != null)
   //             {
   //                 FieldObj field = new FieldObj(voF);
   //                 String columnName = field.GetColumnName();
   //                 //	Record Info
   //                 if (field.IsKey())
   //                     _keyColumnName = columnName;
   //                 //	Parent Column(s)
   //                 if (field.IsParentColumn())
   //                     _parents.Add(columnName);
   //                 //	Order By
   //                 int sortNo = field.GetSortNo();
   //                 if (sortNo == 0)
   //                 { }
   //                 else if (Math.Abs(sortNo) == 1)
   //                 {
   //                     _OrderBys[0] = columnName;
   //                     if (sortNo < 0)
   //                         _OrderBys[0] += " DESC";
   //                 }
   //                 else if (Math.Abs(sortNo) == 2)
   //                 {
   //                     _OrderBys[1] = columnName;
   //                     if (sortNo < 0)
   //                         _OrderBys[1] += " DESC";
   //                 }
   //                 else if (Math.Abs(sortNo) == 3)
   //                 {
   //                     _OrderBys[2] = columnName;
   //                     if (sortNo < 0)
   //                         _OrderBys[2] += " DESC";
   //                 }
   //                 //  Add field
   //                 _gridTable.AddField(field);

   //                 //  List of ColumnNames, this field is dependent on
   //                 List<string> list = field.GetDependentOn();
   //                 for (int i = 0; i < list.Count; i++)
   //                     _depOnField.Insert(list[i], field);   //  ColumnName, Field
   //                 //  Add fields all fields are dependent on
   //                 if (columnName.Equals("IsActive")
   //                     || columnName.Equals("Processed")
   //                     || columnName.Equals("Processing"))
   //                     _depOnField.Insert(columnName, null);
   //             }
   //         }   //  for all fields

   //         //  Add Standard Fields
   //         if (_gridTable.GetField("Created") == null)
   //         {
   //             FieldObj created = new FieldObj(FIELDVO.CreateStdField(_vo.ctx,
   //                 _vo.windowNum, _vo.tabNum,
   //                 _vo.AD_WINDOW_ID, _vo.AD_TAB_ID, false, true, true));
   //             _gridTable.AddField(created);
   //         }
   //         if (_gridTable.GetField("CreatedBy") == null)
   //         {
   //             FieldObj createdBy = new FieldObj(FIELDVO.CreateStdField(_vo.ctx,
   //                 _vo.windowNum, _vo.tabNum,
   //                 _vo.AD_WINDOW_ID, _vo.AD_TAB_ID, false, true, false));
   //             _gridTable.AddField(createdBy);
   //         }
   //         if (_gridTable.GetField("Updated") == null)
   //         {
   //             FieldObj updated = new FieldObj(FIELDVO.CreateStdField(_vo.ctx,
   //                 _vo.windowNum, _vo.tabNum,
   //                 _vo.AD_WINDOW_ID, _vo.AD_TAB_ID, false, false, true));
   //             _gridTable.AddField(updated);
   //         }
   //         if (_gridTable.GetField("UpdatedBy") == null)
   //         {
   //             FieldObj updatedBy = new FieldObj(FIELDVO.CreateStdField(_vo.ctx,
   //                 _vo.windowNum, _vo.tabNum,
   //                 _vo.AD_WINDOW_ID, _vo.AD_TAB_ID, false, false, false));
   //             _gridTable.AddField(updatedBy);
   //         }
   //         return true;
   //     }

   //     /// <summary>
   //     /// Get Link Col Name
   //     /// </summary>
   //     /// <returns></returns>
   //     public string GetLinkColumnName()
   //     {
   //         return _linkColumnName;
   //     }	//	getLinkColumnName

   //     /// <summary>
   //     /// Get Parent COl Names
   //     /// </summary>
   //     /// <returns></returns>
   //     public List<string> GetParentColumnNames()
   //     {
   //         return _parents;
   //     }

   //     /// <summary>
   //     /// Set Link Col Name
   //     /// </summary>
   //     /// <param name="linkColumnName"></param>
   //     public void SetLinkColumnName(string linkColumnName)
   //     {
   //         if (linkColumnName != null)
   //             _linkColumnName = linkColumnName;
   //         else
   //         {
   //             if (_vo.AD_COLUMN_ID == 0)
   //                 return;
   //             //	we have a link column identified (primary parent column)
   //             else
   //             {
   //                 string SQL = "SELECT ColumnName FROM AD_Column WHERE AD_Column_ID=" + _vo.AD_COLUMN_ID;
   //                 try
   //                 {
   //                     _linkColumnName = ExecuteQuery.ExecuteScalar(SQL).ToString();
   //                 }
   //                 catch (Exception e)
   //                 {
   //                     ErrorLog.FillErrorLog("TabObj", SQL, e.Message, VAdvantage.Framework.Message.MessageType.ERROR);
   //                 }
   //                 ErrorLog.FillErrorLog("TabObj", "", "AD_Column_ID=" + _vo.AD_COLUMN_ID + " - " + _linkColumnName, VAdvantage.Framework.Message.MessageType.INFORMATION);
   //             }
   //         }
   //         _vo.ctx.SetContext(_vo.windowNum, _vo.tabNum, "LinkColumnName", _linkColumnName);
   //     }

   //     /// <summary>
   //     /// Is High Volume(show Find Window)
   //     /// </summary>
   //     /// <returns></returns>
   //     public bool IsHighVolume()
   //     {
   //         return _vo.ISHIGHVOLUME;
   //     }








   //     /// <summary>
   //     /// IS Sort Tab
   //     /// </summary>
   //     /// <returns></returns>
   //     public bool IsSortTab()
   //     {
   //         return _vo.ISSORTTAB == 'Y' ? true : false;
   //     }

   //     /**
   //  *  Has Tree
   //  *  @return true if tree exists
   //  */
   //     public bool IsTreeTab()
   //     {
   //         return _vo.HASTREE == 'Y' ? true : false;
   //     }
   //     /// <summary>
   //     /// Get Extended Where Clause
   //     /// </summary>
   //     /// <returns></returns>
   //     public string GetWhereExtended()
   //     {
   //         return _extendedWhere;
   //     }	//	getWhereExtended

   //     /// <summary>
   //     /// Get Tab Where Clause
   //     /// </summary>
   //     /// <returns></returns>
   //     public string GetWhereClause()
   //     {
   //         return _vo.WHERECLAUSE;
   //     }

   //     //Get Table Name
   //     public string GetTableName()
   //     {
   //         return _vo.TABLENAME;
   //     }
   //     //Table Id
   //     public int GetAD_Table_ID()
   //     {
   //         return _vo.AD_TABLE_ID;
   //     }

   //     /// <summary>
   //     ///Return the name of the key column - may be ""
   //     /// </summary>
   //     /// <returns></returns>
   //     public string GetKeyColumnName()
   //     {
   //         return _keyColumnName;
   //     }	//	getKeyColumnName

   //     //return filed by index
   //     public FieldObj GetField(int index)
   //     {
   //         return _gridTable.GetField(index);
   //     }

   //     /// <summary>
   //     /// //return Total Fields in Tab
   //     /// </summary>
   //     /// <returns></returns>
   //     public int GetFieldCount()
   //     {
   //         return _gridTable.GetColumnCount();
   //     }
   //     //Tab ID
   //     public int GetTabID()
   //     {
   //         return _vo.AD_TAB_ID;
   //     }
   //     //Tab Name
   //     public string GetName()
   //     {
   //         return _vo.NAME;
   //     }
   //     //Description
   //     public string GetDescription()
   //     {
   //         return _vo.DESCRIPTION;
   //     }
   //     //Help
   //     public string GetHelp()
   //     {
   //         return _vo.HELP;
   //     }

   //     /**
   //  *  Get Commit Warning
   //  *  @return commit warning
   //  */
   //     public String GetCommitWarning()
   //     {
   //         return _vo.COMMITWARNING;
   //     }



   //     /**
   //  * 	Get Order column for sort tab
   //  * 	@return AD_Column_ID
   //  */
   //     public int GetAD_ColumnSortOrder_ID()
   //     {
   //         return _vo.AD_COLUMNSORTORDER_ID;
   //     }	//	getAD_ColumnSortOrder_ID

   //     /**
   //      * 	Get Yes/No column for sort tab
   //      * 	@return AD_Column_ID
   //      */
   //     public int GetAD_ColumnSortYesNo_ID()
   //     {
   //         return _vo.AD_COLUMNSORTYESNO_ID;
   //     }	//	getAD_ColumnSortYesNo_ID


   //     /*public int GetMaxFieldLenght()
   //     {
   //         return _vo.GetMaxLength();
   //     }*/

   //     /// <summary>
   //     /// Get Field by DB column name
   //     /// </summary>
   //     /// <param name="columnName"></param>
   //     /// <returns></returns>
   //     public FieldObj GetField(string columnName)
   //     {
   //         return _gridTable.GetField(columnName);
   //     }   //  GetField

   //     /// <summary>
   //     ///return fields Array
   //     /// </summary>
   //     /// <returns></returns>
   //     public FieldObj[] GetFields()
   //     {
   //         return _gridTable.GetFields();
   //     }

   //     //Get DataGridView
   //     public VDataGridView.VDataGridView GridTable()
   //     {
   //         return _gridTable.GetTableModal();
   //     }
   //     public TableObj GetTableObj()
   //     {
   //         return _gridTable;
   //     }

   //     //Tab Level
   //     public int GetTabLevel()
   //     {
   //         return _vo.TABLEVEL;
   //     }

   //     public void LateBinding()
   //     {
   //         _gridTable.LateDataBinding();
   //     }

   //     public void EarlyBinding()
   //     {
   //         _gridTable.EarlyDataBinding();
   //     }

   //     /// <summary>
   //     ///	Is the Tab Visible.
   //     ///	Called when constructing the window.
   //     /// </summary>
   //     /// <param name="initialSetup">return false only if not to be displayed</param>
   //     /// <returns>true, if displayed</returns>
   //     public bool IsDisplayed(bool initialSetup)
   //     {
   //         //  no restrictions
   //         String dl = _vo.DISPLAYLOGIC;
   //         if (dl == null || dl.Equals(""))
   //             return true;

   //         if (initialSetup)
   //         {
   //             if (dl.IndexOf("@#") != -1)		//	global variable
   //             {
   //                 String parsed = Utility.Env.ParseContext(_vo.ctx, 0, dl, false, false).Trim();
   //                 if (parsed.Length != 0)	//	variable defined
   //                     return Evaluator.EvaluateLogic(this, dl);
   //             }
   //             return true;
   //         }
   //         //
   //         bool retValue = Evaluator.EvaluateLogic(this, dl);
   //         log.config(m_vo.Name + " (" + dl + ") => " + retValue);
   //         return retValue;
   //     }	//	isDisplayed

   //     /// <summary>
   //     /// load the records and return true if success
   //     /// </summary>
   //     /// <param name="onlyCurrentDays"></param>
   //     /// <param name="maxRows"></param>
   //     /// <param name="created"></param>
   //     /// <returns></returns>
   //     public bool query(int onlyCurrentDays,
   //     int maxRows, bool created)
   //     {
   //         bool success = false;
   //         //  start loading while building screen
   //         success = PrepareQuery(onlyCurrentDays, maxRows, created);
   //         ////  Update UI
   //         //if (!isSingleRow())
   //         //    vTable.autoSize(true);
   //         return success;
   //     }   //  query

   //     /// <summary>
   //     /// Assemble whereClause and query .
   //     ///		Scenarios:
   //     ///	- Never opened 					(full query)
   //     ///		- query changed 				(full query)
   //     ///		- Detail link value changed		(full query)
   //     ///		- otherwise 					(refreshAll)
   //     /// </summary>
   //     /// <param name="onlyCurrentDays">if only current row, how many days back</param>
   //     /// <param name="maxRows">maxRows maximum rows or 0 for all</param>
   //     /// <param name="created">created query based on created if true otherwise updated</param>
   //     /// <returns>true if queried successfully</returns>
   //     public bool PrepareQuery(int onlyCurrentDays, int maxRows, bool created)
   //     {
   //         bool success = true;
   //         //	is it same query?
   //         bool refresh = _oldQuery.Equals(_query.GetWhereClause())
   //             && _vo.OnlyCurrentDays == onlyCurrentDays;

   //         _oldQuery = _query.GetWhereClause();
   //         _vo.OnlyCurrentDays = onlyCurrentDays;

   //         /**
   //        *	Set Where Clause
   //        */
   //         //	Tab Where Clause
   //         StringBuilder where = new StringBuilder(_vo.WHERECLAUSE);
   //         if (_vo.OnlyCurrentDays > 0)
   //         {
   //             if (where.Length > 0)
   //                 where.Append(" AND ");

   //             bool showNotProcessed = FindColumn("Processed") != -1;
   //             //	Show only unprocessed or the one updated within x days
   //             if (showNotProcessed)
   //                 where.Append("(Processed='N' OR ");
   //             if (created)
   //                 where.Append("Created>=");
   //             else
   //                 where.Append("Updated>=");
   //             //	where.append("addDays(current_timestamp, -");
   //             where.Append("addDays(SysDate, -")
   //                 .Append(_vo.OnlyCurrentDays).Append(")");
   //             if (showNotProcessed)
   //                 where.Append(")");
   //         }

   //         if (IsDetail())
   //         {
   //             string lc = GetLinkColumnName();
   //             if (lc.Equals(""))
   //             {
   //                 //log.warning("No link column");
   //                 if (where.Length > 0)
   //                     where.Append(" AND ");
   //                 where.Append(" 2=3");
   //                 success = false;
   //             }
   //             else
   //             {
   //                 string value = _vo.ctx.GetContext(_vo.windowNum, lc);
   //                 //	Same link value?
   //                 if (refresh)
   //                 {
   //                     refresh = _linkValue.Equals(value);
   //                 }
   //                 _linkValue = value;
   //                 //	Check validity
   //                 if (value.Length == 0)
   //                 {
   //                     //log.warning("No value for link column " + lc);
   //                     if (where.Length > 0)
   //                         where.Append(" AND ");
   //                     where.Append(" 2=4");
   //                     success = false;
   //                 }
   //                 else
   //                 {
   //                     //	we have column and value
   //                     if (where.Length > 0)
   //                         where.Append(" AND ");
   //                     if ("NULL".Equals(value.ToUpper()))
   //                     {
   //                         where.Append(lc).Append(" IS NULL ");
   //                         //log.severe("Null Value of link column " + lc);
   //                     }
   //                     else
   //                     {
   //                         where.Append(lc).Append("=");
   //                         if (lc.EndsWith("_ID"))
   //                             where.Append(value);
   //                         else
   //                             where.Append("'").Append(value).Append("'");
   //                     }
   //                 }
   //             }
   //         }	//	isDetail

   //         _extendedWhere = where.ToString();

   //         //	Final Query
   //         if (_query.IsActive())
   //         {
   //             string q = ValidateQuery(_query);
   //             if (q != null)
   //             {
   //                 if (where.Length > 0)
   //                     where.Append(" AND ");
   //                 where.Append(q);
   //             }
   //         }

   //         /**
   //      *	Query
   //      */
   //         //log.fine("#" + m_vo.tabNum + " - " + where);
   //         if (_gridTable.IsOpen())
   //         {
   //             if (refresh)
   //             {
   //                 _gridTable.DataRefreshAll();
   //             }
   //             else
   //                 _gridTable.DataRequery(where.ToString());
   //         }
   //         else
   //         {
   //             _gridTable.SetSelectWhereClause(where.ToString());
   //             _gridTable.Open(maxRows);
   //         }

   //         return success;
   //     }

   //     public DataSet GetDataTable()
   //     {
   //         return _gridTable.GetRecords();
   //     }


   //    /// <summary>
   //    ///Refresh all Rows - ignore changes
	 
	

      

        
        
        
        
   //     /// <summary>
   //     /// Is Single Row
   //     /// </summary>
   //     /// <returns></returns>
   //     public bool IsSingleRow()
   //     {
   //         return (_vo.ISSINGLEROW == 'Y') ? true : false;
   //     }   //

   //     /// <summary>
   //     /// Find Column
   //     /// </summary>
   //     /// <param name="columnName"></param>
   //     /// <returns></returns>
   //     public int FindColumn(string columnName)
   //     {
   //         return _gridTable.FindColumn(columnName);
   //     }

   //     /// <summary>
   //     /// Returns true if this is a detail record
   //     /// </summary>
   //     /// <returns></returns>
   //     public bool IsDetail()
   //     {
   //         //	We have IsParent columns and/or a link column
   //         if (_parents.Count > 0 || _vo.AD_COLUMN_ID != 0)
   //             return true;
   //         return false;
   //     }	//	IsDetail

   //     /// <summary>
   //     /* 
   //      *	Is the tab current?.
   //      *  <pre>
   //      *	Yes 	- Table must be open
   //      *			- Query String is the same
   //      *			- Not Detail
   //      *			- Old link column value is same as current one
   //      *  </pre>
   //      *  @return true if current
   //      */
   //     /// </summary>
   //     /// <returns></returns>
   //     public bool IsCurrent()
   //     {
   //         //	Open?
   //         if (!_gridTable.IsOpen())
   //             return false;
   //         //	Same Query
   //         if (!_oldQuery.Equals(_query.GetWhereClause()))
   //             return false;
   //         //	Detail?
   //         if (!IsDetail())
   //             return true;
   //         //	Same link column value
   //         String value = _vo.ctx.GetContext(_vo.windowNum, GetLinkColumnName());
   //         return _linkValue.Equals(value);
   //     }	//	isCurrent

   //     /// <summary>
   //     /// Validate Query.
   //     /// If query column is not a tab column create EXISTS query
   //     /// </summary>
   //     /// <param name="query">query</param>
   //     /// <returns>where clause</returns>
   //     private String ValidateQuery(Query query)
   //     {
   //         if (query == null || query.GetRestrictionCount() == 0)
   //             return null;

   //         //	Check: only one restriction
   //         if (query.GetRestrictionCount() != 1)
   //         {
   //             //log.fine("Ignored(More than 1 Restriction): " + query);
   //             return query.GetWhereClause();
   //         }

   //         String colName = query.GetColumnName(0);
   //         if (colName == null)
   //         {
   //             //log.fine("Ignored(No Column): " + query);
   //             return query.GetWhereClause();
   //         }
   //         //	a '(' in the name = function - don't try to resolve
   //         if (colName.IndexOf('(') != -1)
   //         {
   //             //log.fine("Ignored(Function): " + colName);
   //             return query.GetWhereClause();
   //         }
   //         ////	OK - Query is valid 

   //         //	Zooms to the same Window (Parents, ..)
   //         String refColName = null;
   //         if (colName.Equals("R_RequestRelated_ID"))
   //             refColName = "R_Request_ID";
   //         else if (colName.StartsWith("C_DocType"))
   //             refColName = "C_DocType_ID";
   //         else if (colName.Equals("CreatedBy") || colName.Equals("UpdatedBy"))
   //             refColName = "AD_User_ID";
   //         else if (colName.Equals("Orig_Order_ID"))
   //             refColName = "C_Order_ID";
   //         else if (colName.Equals("Orig_InOut_ID"))
   //             refColName = "M_InOut_ID";
   //         if (refColName != null)
   //         {
   //             query.SetColumnName(0, refColName);
   //             if (GetField(refColName) != null)
   //             {
   //                 //log.fine("Column " + colName + " replaced with synonym " + refColName);
   //                 return query.GetWhereClause();
   //             }
   //             refColName = null;
   //         }

   //         ////	Simple Query. 
   //         if (GetField(colName) != null)
   //         {
   //             //log.fine("Field Found: " + colName);
   //             return query.GetWhereClause();
   //         }

   //         //	Find Refernce Column e.g. BillTo_ID -> C_BPartner_Location_ID
   //         string sql = "SELECT cc.ColumnName "
   //             + "FROM AD_Column c"
   //             + " INNER JOIN AD_Ref_Table r ON (c.AD_Reference_Value_ID=r.AD_Reference_ID)"
   //             + " INNER JOIN AD_Column cc ON (r.Column_Key_ID=cc.AD_Column_ID) "
   //             + "WHERE c.AD_Reference_ID IN (18,30)" 	//	Table/Search
   //             + " AND c.ColumnName='" + colName + "'";
   //         IDataReader dr = null;
   //         try
   //         {
   //             dr = ExecuteQuery.ExecuteReader(sql);
   //             if (dr.Read())
   //                 refColName = dr["ColumnName"].ToString();
   //             dr.Close();
   //         }
   //         catch (Exception e)
   //         {
   //             dr.Close();
   //             ErrorLog.FillErrorLog("TabObj.ValidateQuery", "(ref) - Column=" + colName, e.Message, VAdvantage.Framework.Message.MessageType.ERROR);
   //             return query.GetWhereClause();
   //         }
   //         //	Reference Column found
   //         if (refColName != null)
   //         {
   //             query.SetColumnName(0, refColName);
   //             if (GetField(refColName) != null)
   //             {
   //                 //log.fine("Column " + colName + " replaced with " + refColName);
   //                 return query.GetWhereClause();
   //             }
   //             colName = refColName;
   //         }

   //         //	Column NOT in Tab - create EXISTS subquery
   //         String tableName = null;
   //         String tabKeyColumn = GetKeyColumnName();
   //         ////	Column=SalesRep_ID, Key=AD_User_ID, Query=SalesRep_ID=101

   //         sql = "SELECT t.TableName "
   //             + "FROM AD_Column c"
   //             + " INNER JOIN AD_Table t ON (c.AD_Table_ID=t.AD_Table_ID) "
   //             + "WHERE c.ColumnName='" + colName + "' AND IsKey='Y'"		//	#1 Link Column
   //             + " AND EXISTS (SELECT * FROM AD_Column cc"
   //             + " WHERE cc.AD_Table_ID=t.AD_Table_ID AND cc.ColumnName='" + tabKeyColumn + "')";	//	#2 Tab Key Column
   //         try
   //         {
   //             dr = ExecuteQuery.ExecuteReader(sql);
   //             if (dr.Read())
   //                 tableName = dr["TableName"].ToString();
   //             dr.Close();
   //         }
   //         catch (Exception e)
   //         {
   //             dr.Close();
   //             ErrorLog.FillErrorLog("TabObj.ValidateQuery", "Column=" + colName + ", Key=" + tabKeyColumn, e.Message, VAdvantage.Framework.Message.MessageType.ERROR);
   //             return null;
   //         }

   //         //	Special Reference Handling
   //         if (tabKeyColumn.Equals("AD_Reference_ID"))
   //         {
   //             //	Column=AccessLevel, Key=AD_Reference_ID, Query=AccessLevel='6'
   //             sql = "SELECT AD_Reference_ID FROM AD_Column WHERE ColumnName='" + colName + "'";
   //             //int AD_Reference_ID = DB.getSQLValue(null, sql, colName);
   //             string AD_Reference_ID = ExecuteQuery.ExecuteScalar(sql).ToString();
   //             return "AD_Reference_ID=" + AD_Reference_ID;
   //         }

   //         ////	Causes could be functions in query
   //         ////	e.g. Column=UPPER(Name), Key=AD_Element_ID, Query=UPPER(AD_Element.Name) LIKE '%CUSTOMER%'
   //         if (tableName == null)
   //         {
   //             ErrorLog.FillErrorLog("TabObj.ValidateQuery", "Not successfull - Column=" + colName + ", Key=" + tabKeyColumn + ", Query=" + query, "", VAdvantage.Framework.Message.MessageType.INFORMATION);
   //             return query.GetWhereClause();
   //         }

   //         query.SetTableName("xx");
   //         StringBuilder result = new StringBuilder("EXISTS (SELECT * FROM ")
   //             .Append(tableName).Append(" xx WHERE ")
   //             .Append(query.GetWhereClause(true))
   //             .Append(" AND xx.").Append(tabKeyColumn).Append("=")
   //             .Append(GetTableName()).Append(".").Append(tabKeyColumn).Append(")");

   //         return result.ToString();
   //     }

   //     /// <summary>
   //     /// Get Only Current Days
   //     /// </summary>
   //     /// <returns></returns>
   //     public int GetOnlyCurrentDays()
   //     {
   //         return _vo.OnlyCurrentDays;
   //     }

   //     //Set Query Object
   //     public void SetQuery(Query query)
   //     {
   //         if (query == null)
   //             _query = new Query();
   //         else
   //         {
   //             _query = query;
   //             _vo.OnlyCurrentDays = 0;
   //         }
   //     }


   //     /// <summary>
   //     /// 
   //     /// </summary>
   //     /// <param name="variableName"></param>
   //     /// <returns></returns>
   //     public String GetValueAsString(String variableName)
   //     {
   //         return _vo.ctx.GetContext(_vo.windowNum, variableName, true);
   //     }



   //     // Contain All COntrols of window 
   //     public List<Control> controlList = new List<Control>();

   //     public List<Control> GetControls()
   //     {
   //         return controlList;
   //     }
   //     /// <summary>
   //     /// Bind Control With Binding Source
   //     /// </summary>
   //     /// <param name="bindSorce"></param>
   //     public void BindControls(BindingSource bindSorce)
   //     {
   //         for (int i = 0; i < controlList.Count; i++)
   //         {
   //             Control oo = controlList[i];
   //             //if (oo.GetType().ToString().ToLower().Contains("label"))
   //             //{
   //             //    continue;
   //             //}
   //             if (oo.GetType().ToString().ToLower().Contains("vaddresstextbox"))
   //             {
   //                 oo.DataBindings.Add("C_Location_ID", bindSorce, oo.Name, true);
   //             }
   //             else if (oo.GetType().ToString().ToLower().Contains("textbox"))
   //             {
   //                 oo.DataBindings.Add("Text", bindSorce, oo.Name, true);
   //             }
   //             else if (oo.GetType().ToString().ToLower().Contains("checkbox"))
   //             {
   //                 oo.DataBindings.Add("Checked", bindSorce, oo.Name, true);
   //             }
   //             else if (oo.GetType().ToString().ToLower().Contains("combobox"))
   //             {
   //                 //((VAdvantage.Controls.VComboBox)oo).SetValue(((DataRowView)bindSorce.Current)[oo.Name]);
   //                 oo.DataBindings.Add("ComboSetValue", bindSorce, oo.Name, true);
   //             }
   //             else if (oo.GetType().ToString().ToLower().Contains("button"))
   //             {
   //                 oo.DataBindings.Add("BtnValue", bindSorce, oo.Name, true);
   //             }
   //             else if (oo.GetType().ToString().ToLower().Contains("datetime"))
   //             {
   //                 oo.DataBindings.Add("Value", bindSorce, oo.Name, true);
   //             }
   //         }
   //     }

   //     /// <summary>
   //     /// Remove Data Binding to control 
   //     /// </summary>
   //     public void RemoveBinding()
   //     {
   //         for (int i = 0; i < controlList.Count; i++)
   //         {
   //             Control oo = controlList[i];
   //             //                if (oo.GetType().ToString().ToLower().Contains("textbox"))
   //             //              {
   //             oo.DataBindings.Clear();
   //             //            }
   //         }
   //     }

   //     public int GetKeyIndex()
   //     {
   //         return _gridTable.GetKeyIndex();
   //     }
   //     public void SetOriginalData(DataRowView drv)
   //     {
   //         _gridTable.SetOriginalData(drv);
   //     }

   //     /// <summary>
   //     /// Do we need to Save?
   //     /// </summary>
   //     /// <param name="rowChange"></param>
   //     /// <param name="onlyRealChange"></param>
   //     /// <returns></returns>
   //     public bool NeedSave(bool rowChange, bool onlyRealChange)
   //     {
   //         if (rowChange)
   //         {
   //             return _gridTable.NeedSave(-2, onlyRealChange);
   //         }
   //         else
   //         {
   //             //if (onlyRealChange)
   //             //    return m_mTable.needSave();
   //             //else
   //             //    return m_mTable.needSave(onlyRealChange);
   //             return false;
   //         }
   //     }

   //     /// <summary>
   //     ///Uncoditionally Save data
   //     /// </summary>
   //     /// <param name="manualCmd"></param>
   //     /// <returns></returns>
   //     public bool DataSave(bool manualCmd, DataRowView drv)
   //     {
   //         //log.fine("#" + m_vo.TabNo + " - row=" + m_currentRow);
   //         try
   //         {
   //             bool retValue = (_gridTable.DataSave(manualCmd, drv) == TableObj.SAVE_OK);
   //             //if (manualCmd)
   //             //    setCurrentRow(m_currentRow, false);
   //             return retValue;
   //         }
   //         catch (Exception e)
   //         {
   //             Common.ErrorLog.FillErrorLog("Save", "", e.Message, VAdvantage.Framework.Message.MessageType.ERROR);
   //             log.log(Level.SEVERE, "#" + m_vo.TabNo + " - row=" + m_currentRow, e);
   //         }
   //         return false;
   //     }   //  dataSave


   //     /// <summary>
   //     ///Check User can Insert record
   //     /// </summary>
   //     /// <param name="copy">copy</param>
   //     /// <returns>true if copied/new</returns>
   //     public bool CheckDataNew()
   //     {
   //         //log.fine("#" + m_vo.TabNo);
   //         if (!IsInsertRecord())
   //         {
   //             //log.warning("Inset Not allowed in TabNo=" + m_vo.TabNo);
   //             return false;
   //         }
   //         //	Prevent New Where Main Record is processed
   //         if (_vo.tabNum > 0)
   //         {
   //             bool processed = "Y".Equals(_vo.ctx.GetContext(_vo.windowNum, "Processed"));
   //             //	boolean active = "Y".equals(m_vo.ctx.getContext( m_vo.WindowNo, "IsActive"));
   //             if (processed)
   //             {
   //                 //log.warning("Not allowed in TabNo=" + m_vo.TabNo + " -> Processed=" + processed);
   //                 return false;
   //             }
   //             //log.finest("Processed=" + processed);
   //         }
   //         return true;
   //     }

   //     public bool DataNew(bool copy, DataRowView drv)
   //     {
   //         bool retValue = _gridTable.DataNew(copy, drv);
   //         if (!retValue)
   //         {
   //             return retValue;
   //         }

   //         //    setCurrentRow(m_currentRow + 1, true);
   //         //    //  process all Callouts (no dependency check - assumed that settings are valid)
   //         //for (int i = 0; i < GetFieldCount(); i++)
   //         //     ProcessCallout(GetField(i));
   //         //  check validity of defaults
   //         //for (int i = 0; i < GetFieldCount(); i++)
   //         //{
   //         //    ////GetField(i) . refreshLookup();
   //         //    //GetField(i) .validateValue();
   //         //    //getField(i).setError(false);
   //         //}
   //         ////    m_mTable.setChanged(false);
   //         return retValue;
   //         //}   //  dataNew
   //     }

   //     public void PerformCallout()
   //     {
   //         for (int i = 0; i < GetFieldCount(); i++)
   //             ProcessCallout(GetField(i));
   //     }

   //     /// <summary>
   //     /// Can we Insert Records?
   //     /// </summary>
   //     /// <returns>true not read only and allowed</returns>
   //     public bool IsInsertRecord()
   //     {
   //         if (IsReadOnly())
   //             return false;
   //         return (_vo.ISINSERTRECORD == 'Y') ? true : false;
   //     }	//	

   //     /// <summary>
   //     /// Delete current Row
   //     /// </summary>
   //     /// <returns>true if deleted</returns>
   //     public bool DataDelete(int _currentRow)
   //     {
   //         //log.fine("#" + m_vo.TabNo + " - row=" + m_currentRow);
   //         bool retValue = _gridTable.DataDelete(_currentRow);
   //         //setCurrentRow(m_currentRow, true);
   //         return retValue;
   //     }   //  dataDelete


   //     /// <summary>
   //     /// Has this field dependents ?
   //     /// </summary>
   //     /// <param name="columnName">column name</param>
   //     /// <returns>true if column has dependent</returns>
   //     public bool HasDependants(String columnName)
   //     {
   //         return _depOnField.ContainsKey(columnName);
   //     }   //  IsDependentOn

   //     /// <summary>
   //     ///Get dependents fields of columnName
   //     /// </summary>
   //     /// <param name="columnName">key</param>
   //     /// <returns>List with GridFields dependent on columnName</returns>
   //     public List<FieldObj> GetDependantFields(String columnName)
   //     {
   //         return _depOnField.GetValues(columnName);
   //     }   //  GetDependantFields

   //    /// <summary>
   //    /// Load Dependant Information
   //    /// </summary>
   //    public void LoadDependentInfo()
   //     {
   //         /**
   //          * Load Order Type from C_DocTypeTarget_ID
   //          */
   //         if (_vo.TABLENAME.Equals("C_Order"))
   //         {
   //             int C_DocTyp_ID = 0;
   //             //int target = (Integer)GetValue("C_DocTypeTarget_ID");
   //             if (GetValue("C_DocTypeTarget_ID") == null)
   //                 return;

   //             int.TryParse(GetValue("C_DocTypeTarget_ID").ToString(), out C_DocTyp_ID);
                
   //             if (C_DocTyp_ID == 0)
   //                 return;

   //             String sql = "SELECT DocSubTypeSO FROM C_DocType WHERE C_DocType_ID="+C_DocTyp_ID;
   //             try
   //             {
   //                 string orderType = DataBase.DB.ExecuteScalar(sql).ToString();
   //                _vo.ctx.SetContext(_vo.windowNum, "OrderType", orderType);
   //             }
   //             catch (Exception e)
   //             {
   //                 Common.ErrorLog.FillErrorLog("GridTab.LoadDependentInfo", sql, e.Message, VAdvantage.Framework.Message.MessageType.ERROR);
   //             }
   //         }   //  loadOrderInfo
   //     }   //  loadDependentInfo

   //     /// <summary>
   //     ///Is Read Only?
   //     /// </summary>
   //     /// <returns>true if read only</returns>
   //     public bool IsReadOnly()
   //     {
   //         if (_vo.ISREADONLY == 'Y')
   //             return true;

   //         //  no restrictions
   //         if (_vo.READONLYLOGIC == null || _vo.READONLYLOGIC.Equals(""))
   //             return (_vo.ISREADONLY == 'Y') ? true : false;

   //         //  ** dynamic content **  uses get_ValueAsString Not Implement yet
   //         bool retValue = Evaluator.EvaluateLogic(this, _vo.READONLYLOGIC);
   //         //log.finest(m_vo.Name
   //         //    + " (" + m_vo.ReadOnlyLogic + ") => " + retValue);
   //         return retValue;
   //     }	//	isReadOnly

   //     /// <summary>
   //     ///	Tab contains Always Update Field
   //     /// </summary>
   //     /// <returns></returns>
   //     public bool IsAlwaysUpdateField()
   //     {
   //         int size = _gridTable.GetColumnCount();
   //         for (int i = 0; i < size; i++)
   //         {
   //             FieldObj field = _gridTable.GetField(i);
   //             if (field.IsAlwaysUpdateable())
   //                 return true;
   //         }
   //         return false;
   //     }	//


   //     /// <summary>
   //     /// Is Query Active
   //     /// </summary>
   //     /// <returns>true if query active</returns>
   //     public bool IsQueryActive()
   //     {
   //         if (_query != null)
   //             return _query.IsActive();
   //         return false;
   //     }

   //     /// <summary>
   //     ///    Is Query New Record
   //     /// </summary>
   //     /// <returns></returns>
   //     public bool IsQueryNewRecord()
   //     {
   //         if (_query != null)
   //             return _query.IsNewRecordQuery();
   //         return false;
   //     }	//	isQueryNewRecord



   //     /// <summary>
   //     /// Get Tab ID
   //     /// </summary>
   //     /// <returns>Tab ID</returns>
   //     public int GetAD_Tab_ID()
   //     {
   //         return _vo.AD_TAB_ID;
   //     }

   //     /// <summary>
   //     /// Get TabNo
   //     /// </summary>
   //     /// <returns>tab no</returns>
   //     public int GetTabNo()
   //     {
   //         return _vo.tabNum;
   //     }

   //     /// <summary>
   //     /// Get ProcessID
   //     /// </summary>
   //     /// <returns>ProcessID</returns>
   //     public int GetAD_Process_ID()
   //     {
   //         return _vo.AD_PROCESS_ID;
   //     }

   //     /// <summary>
   //     /// Get Current Table Key ID
   //     /// </summary>
   //     /// <returns>Record_ID</returns>
   //     /// <author>Veena Pandey</author>
   //     public int GetRecord_ID()
   //     {
   //         return _gridTable.GetKeyID(CurrentRow);
   //     }

   //     /// <summary>
   //     /// Get Attachment_ID for current record.
   //     /// </summary>
   //     /// <returns>ID or 0, if not found</returns>
   //     /// <author>Veena Pandey</author>
   //     public int GetAD_AttachmentID()
   //     {
   //         if (_attachments == null)
   //             LoadAttachments();
   //         if (_attachments == null)
   //             return 0;
   //         //
   //         int key = _gridTable.GetKeyID(CurrentRow);
   //         //int value = int.Parse(_attachments[key].ToString());
   //         if (_attachments.ContainsKey(key))
   //         {
   //             int value = int.Parse(_attachments[key].ToString());
   //             return value;
   //         }
   //         return 0;
   //     }

   //     /// <summary>
   //     /// Returns true, if current row has an Attachment
   //     /// </summary>
   //     /// <returns>bool type true if record has attachment</returns>
   //     /// <author>Veena Pandey</author>
   //     public bool HasAttachment()
   //     {
   //         if (_attachments == null)
   //             LoadAttachments();
   //         if (_attachments == null)
   //             return false;
   //         //
   //         int key = _gridTable.GetKeyID(CurrentRow);
   //         return _attachments.ContainsKey(key);
   //     }

   //     /// <summary>
   //     /// Can this tab have Attachments?.
   //     /// </summary>
   //     /// <returns>bool type true if record can have attachment</returns>
   //     /// <author>Veena Pandey</author>
   //     public bool CanHaveAttachment()
   //     {
   //         if (GetKeyColumnName().EndsWith("_ID"))
   //             return true;
   //         return false;
   //     }

   //     /// <summary>
   //     /// Load Attachments for this table
   //     /// </summary>
   //     /// <author>Veena Pandey</author>
   //     public void LoadAttachments()
   //     {
   //         //log.fine("#" + m_vo.TabNo);
   //         if (!CanHaveAttachment())
   //             return;

   //         string sqlQry = "SELECT AD_Attachment_ID, Record_ID FROM AD_Attachment "
   //             + "WHERE AD_Table_ID=" + _vo.AD_TABLE_ID;
   //         try
   //         {
   //             if (_attachments == null)
   //                 _attachments = new SortedList<int, int>();
   //             else
   //                 _attachments.Clear();

   //             IDataReader dr = ExecuteQuery.ExecuteReader(sqlQry);
   //             int key, value;
   //             while (dr.Read())
   //             {
   //                 key = Utility.Util.GetValueOfInt(dr["Record_ID"].ToString());
   //                 value = Utility.Util.GetValueOfInt(dr["AD_Attachment_ID"].ToString());
   //                 _attachments.Add(key, value);
   //             }
   //             dr.Close();

   //         }
   //         catch (Exception ex)
   //         {
   //             log.log(Level.SEVERE, "loadAttachments", e);
   //         }
   //         log.config("#" + _attachments.size());
   //     }

   //     /****************************************************************/
   //     #region Load Chat
   //     /// <summary>
   //     /// Load Chats for this table
   //     /// </summary>
   //     /// <author>Raghunandan Sharma</author>
   //     public void LoadChats()
   //     {
   //         //if doesn't have attachment
   //         if (!CanHaveAttachment())
   //             return;//return nothing
   //         //set query
   //         string sql = "SELECT CM_Chat_ID, Record_ID FROM CM_Chat "
   //             + "WHERE AD_Table_ID=" + _vo.AD_TABLE_ID;
   //         try
   //         {
   //             if (_chats == null)
   //                 //create new list for chat
   //                 _chats = new SortedList<int, int>();
   //             else
   //                 //if contain chat then clear list
   //                 _chats.Clear();
   //             //execute query
   //             IDataReader dr = ExecuteQuery.ExecuteReader(sql);
   //             int key, value;//for recordId and chatId
   //             while (dr.Read())
   //             {
   //                 key = Utility.Util.GetValueOfInt(dr["Record_ID"].ToString());
   //                 value = Utility.Util.GetValueOfInt(dr["CM_Chat_ID"].ToString());
   //                 _chats.Add(key, value);
   //             }
   //             dr.Close();
   //         }
   //         catch (Exception e)
   //         {
   //             MessageBox.Show("No Chat");
   //             log.log(Level.SEVERE, sql, e);
   //         }
   //     }
   //     #endregion

   //     #region Has Chat
   //     /// <summary>
   //     /// Returns true, if current row has a Chat
   //     /// </summary>
   //     /// <author>Raghunandan Sharma</author>
   //     /// <returns>Bool Type (return true if record has chat)</returns>
   //     public Boolean HasChat()
   //     {
   //         if (_chats == null)
   //             LoadChats();//call load chat function
   //         if (_chats == null || _chats == null)
   //             return false;
   //         //get chat id
   //         int key = _gridTable.GetKeyID(CurrentRow);
   //         return _chats.ContainsKey(key);//return chatId
   //     }
   //     #endregion

   //     #region Get Chat ID
   //     /// <summary>
   //     ///Get Chat_ID for this record.
   //     /// </summary>
   //     /// <returns>return ID or 0, if not found</returns>
   //     /// <author>Raghunandan Sharma</author>
   //     public int GetCM_ChatID()
   //     {
   //         if (_chats == null)
   //             LoadChats();//call chat function
   //         if (_chats == null)
   //             return 0;
   //         //get chatId
   //         int key = _gridTable.GetKeyID(CurrentRow);
   //         //The given key was not present in the dictionary. Error
   //         //int value = int.Parse(_chats[key].ToString());
   //         if (_chats.ContainsKey(key))
   //         {
   //             //get chat key value
   //             int value = int.Parse(_chats[key].ToString());
   //             return value;
   //         }
   //         return 0;
   //         //if (value.Equals(null))
   //         //    return 0;
   //         //else
   //         //    return value;
   //     }
   //     #endregion

   //     /// <summary>
   //     /// Get Value of Field with columnName
   //     /// </summary>
   //     /// <param name="columnName">column name</param>
   //     /// <returns>value</returns>
   //     public Object GetValue(String columnName)
   //     {
   //         if (columnName == null)
   //             return null;
   //         //int colInd = _gridTable.FindColumn(columnName);
   //         //return _gridTable.GetValueAt(CurrentRow, colInd);
   //         FieldObj field = _gridTable.GetField(columnName);
   //         return GetValue(field);
   //     }

   //     /// <summary>
   //     /// Get Value of Field
   //     /// </summary>
   //     /// <param name="field">field</param>
   //     /// <returns>value</returns>
   //     public Object GetValue(FieldObj field)
   //     {
   //         if (field == null)
   //             return null;
   //         //return GetValue(field.GetColumnName());           
   //         return field.GetValue();
   //     }

   //     /// <summary>
   //     /// Set New Value & call Callout
   //     /// </summary>
   //     /// <param name="columnName">database column name</param>
   //     /// <param name="value">value</param>
   //     /// <returns>error message or ""</returns>
   //     public String SetValue(String columnName, Object value)
   //     {
   //         if (columnName == null)
   //             return "NoColumn";
   //         return SetValue(_gridTable.GetField(columnName), value);
   //     }

   //     /// <summary>
   //     /// Set New Value & call Callout
   //     /// </summary>
   //     /// <param name="field">field</param>
   //     /// <param name="value">value</param>
   //     /// <returns>error message or ""</returns>
   //     public String SetValue(FieldObj field, Object value)
   //     {
   //         if (field == null)
   //             return "NoField";

   //         //log.fine(field.GetColumnName() + "=" + value + " - Row=" + CurrentRow);
   //         try
   //         {
   //            if(value == null)
   //            {
   //                //value != null ? value : DBNull.Value;
   //                value = DBNull.Value;
   //            }
   //             _rowData[field.GetColumnName()] = value;
   //            //_rowData.Row[field.GetColumnName()] = value;
   //             field.SetValue(value, false);
   //             if (!_isCalloutExecute)
   //             {
   //                 _rowData.EndEdit();
   //             }
   //             IsRowDirty = true;
                
   //             //GridTable().NotifyCurrentCellDirty(true);
   //             //_gridTable.GetTableModal().NotifyCurrentCellDirty(true);
   //             if (!CalloutEngine.IsCalloutActive())
   //             {
   //                 return ProcessFieldChange(field);
   //             }
   //         }
   //         catch (Exception ex)
   //         {
   //             ErrorLog.FillErrorLog("TabObj", "", ex.Message, VAdvantage.Framework.Message.MessageType.ERROR);
   //         }

   //         //int col = _gridTable.FindColumn(field.GetColumnName());

   //         //_gridTable.SetValueAt(value, CurrentRow, col, false);

   //         //string coln = field.GetColumnName();
   //         //for (int i = 0; i < controlList.Count; i++)
   //         //{
   //         //    Control oo = controlList[i];
   //         //    if (oo.Name == coln)
   //         //    {
   //         //        Controls.IControl ic = (Controls.IControl)oo;
   //         //        ic.SetValue(value);
   //         //        break;
   //         //    }
   //         //}
   //         //
   //         return "";

   //     }

   //     /// <summary>
   //     /// Process Field Change - evaluate Dependencies and process Callouts.
   //     /// called from MTab.setValue or GridController.dataStatusChanged
   //     /// </summary>
   //     /// <param name="changedField">changed field</param>
   //     /// <returns>error message or ""</returns>
   //     public String ProcessFieldChange(FieldObj changedField)
   //     {
   //         ProcessDependencies(changedField);
   //         return ProcessCallout(changedField);
   //     }

   //     /// <summary>
   //     /// Evaluate Dependencies
   //     /// </summary>
   //     /// <param name="changedField">changed field</param>
   //     private void ProcessDependencies(FieldObj changedField)
   //     {
   //         String columnName = changedField.GetColumnName();
   //         //	log.trace(log.l4_Data, "Changed Column", columnName);

   //         //  when column name is not in list of DependentOn fields - fini
   //         if (!HasDependants(columnName))
   //             return;

   //         //  Get dependent MFields (may be because of display or dynamic lookup)
   //         List<FieldObj> list = GetDependantFields(columnName);
   //         for (int i = 0; i < list.Count; i++)
   //         {
   //             FieldObj dependentField = (FieldObj)list[i];
   //             //	log.trace(log.l5_DData, "Dependent Field", dependentField==null ? "null" : dependentField.getColumnName());
   //             //  if the field has a lookup

   //             if (dependentField.GetLookup() != null && dependentField != null && dependentField.GetLookup().GetType() == typeof(MLookup))
   //             {
   //                 MLookup mLookup = (MLookup)dependentField.GetLookup();
   //                 //	log.trace(log.l6_Database, "Lookup Validation", mLookup.getValidation());
   //                 //  if the lookup is dynamic (i.e. contains this columnName as variable)
   //                 if (mLookup.GetValidation().IndexOf("@" + columnName + "@") != -1)
   //                 {
   //                     //log.fine(columnName + " changed - " + dependentField.GetColumnName() + " set to null");
   //                     //  invalidate current selection
   //                     SetValue(dependentField, null);
   //                 }
   //             }
   //             //if (dependentField != null && dependentField.GetLookup().GetType() == typeof(MLocatorLookup))
   //             {
   //                 // gwu: invalidate currently selected locator if any dependent fields changed
   //                 //MLocatorLookup locLookup = (MLocatorLookup) dependentField.GetLookup();
   //                 //int valueAsInt = 0;
   //                 //if (changedField.GetValue() != null && changedField.GetValue() == typeof(int))// instanceof Number )
   //                 //{
   //                 //   // valueAsInt = ((Number)changedField.GetValue()).intValue();
   //                 //}
   //                 //if( columnName.Equals( "M_Warehouse_ID" ) )
   //                 //{
   //                 //    //locLookup.setOnly_Warehouse_ID( valueAsInt );
   //                 //}
   //                 //if( columnName.Equals( "M_Product_ID" ) )
   //                 //{
   //                 //    //locLookup.setOnly_Product_ID( valueAsInt );
   //                 //}
   //                // locLookup.setOnly_Outgoing(Env.getCtx().isSOTrx(m_vo.WindowNo ));
   //                 //locLookup.refresh();
   //                 //if (!locLookup.isValid(dependentField.getValue()))
   //                 //{
   //                 //    SetValue(dependentField, null);
   //                 //}
   //             }
   //         }
   //     }

   //     /// <summary>
   //     /// Is Processed
   //     /// </summary>
   //     /// <returns>true if current record is processed</returns>
   //     public bool IsProcessed()
   //     {
   //         int index = _gridTable.FindColumn("Processed");
   //         if (index != -1)
   //         {
   //             Object oo = _rowData[index];// _gridTable.GetValueAt(CurrentRow, index);
   //             if (oo.GetType() == typeof(String))
   //                 return "Y".Equals(oo) || "True".Equals(oo);
   //             if (oo.GetType() == typeof(Boolean))
   //                 return ((Boolean)oo);
   //         }
   //         return "Y".Equals(_vo.ctx.GetContext(_vo.windowNum, "Processed"));
   //     }

   //     /// <summary>
   //     /// Process Callout(s).
   //     /// The Callout is in the string of "class.method;class.method;"
   //     /// If there is no class name, i.e. only a method name, the class is regarded as CalloutSystem.
   //     /// The class needs to comply with the Interface Callout.
   //     /// </summary>
   //     /// <param name="field">field</param>
   //     /// <returns>error message or ""</returns>
   //     private String ProcessCallout(FieldObj field)
   //     {
   //         String callout = field.GetCallout();

   //         if (callout == null || callout.Length == 0)
   //         {
   //             return "";
   //         }

   //         if (IsProcessed())		//	only active records
   //             return "";			//	"DocProcessed";

   //         callout = callout.Replace("org.compiere", "VAdvantage");
   //         Object value = field.GetValue();
   //         Object oldValue = field.GetOldValue();
   //         try
   //         {
   //             if (value.ToString() == oldValue.ToString())
   //             {
   //                 return "";
   //             }
   //             _rowData.BeginEdit();
   //             _rowData[field.GetColumnName()] = value;
   //         }
   //         catch
   //         {
   //         }

   //         //log.fine(field.GetColumnName() + "=" + value + " (" + callout + ") - old=" + oldValue);

   //         StringTokenizer st = new StringTokenizer(callout, ";,", false);
   //         while (st.HasMoreTokens())      //  for each callout
   //         {
   //             String cmd = st.NextToken().Trim();
   //             Callout call = null;
   //             String method = null;
   //             int methodStart = cmd.LastIndexOf(".");
   //             try
   //             {
   //                 if (methodStart != -1)      //  no class
   //                 {
   //                     //Class<?> cClass = Class.forName(cmd.Substring(0,methodStart));
   //                     //call = (Callout)cClass.newInstance();
   //                     //method = cmd.Substring(methodStart+1);

   //                     //System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFrom(DataBase.GlobalVariable.ASSEMBLY_NAME);
   //                     Type type = Type.GetType(cmd.Substring(0, methodStart));
   //                     //if (type.IsClass)
   //                     {
   //                         call = (Callout)Activator.CreateInstance(type);
   //                     }
   //                     method = cmd.Substring(methodStart + 1);
   //                 }
   //             }
   //             catch (Exception e)
   //             {
   //                 log.log(Level.SEVERE, "class", e);
   //                 return "Callout Invalid: " + cmd + " (" + e.ToString() + ")";
   //             }

   //             if (call == null || method == null || method.Length == 0)
   //                 return "Callout Invalid: " + method;

   //             String retValue = "";
   //             try
   //             {
   //                 retValue = call.Start(_vo.ctx, method, _vo.windowNum, this, field, value, oldValue);
   //             }
   //             catch (Exception e)
   //             {
   //                 log.log(Level.SEVERE, "start", e);
   //                 retValue = "Callout Invalid: " + e.ToString();
   //                 return retValue;
   //             }
   //             if (!retValue.Equals(""))		//	interrupt on first error
   //             {
   //                 //log.warning (retValue);
   //                 return retValue;
   //             }
   //         }
   //         return "";
   //     }


   //     public bool ProcessDependentAndCallOut(FieldObj mField)
   //     {
   //         //  Process Callout
   //         _isCalloutExecute = true;
   //         bool ret = false; 
   //         if (mField != null && mField.GetCallout().Length > 0)
   //         {

   //             String msg = ProcessFieldChange(mField);     //  Dependencies & Callout
   //             if (msg.Length > 0)
   //             {
   //                 VAdvantage.Classes.ShowMessage.Error(msg, true);
   //                 ret =  false;
   //             }
   //             else
   //             {
   //                 ret =  true;
   //             }
   //         }
   //         _isCalloutExecute = false;
   //         //if (_rowData.IsEdit)
   //         //{
   //         //    _rowData.EndEdit();
   //         //}
   //         return ret;
   //     }


   //     /****************************************************************/
   // }

#endregion


   /*********************************************************************************
     * 
     * Class Fieldtype
     * 
     * *******************************************************************************/
    public class FieldType
    {

        #region "Declaration"
        /** Display Type 10	String	*/
        public static int String = 10;
        /** Display Type 11	Integer	*/
        public static int Integer = 11;
        /** Display Type 12	Amount	*/
        public static int Amount = 12;
        /** Display Type 13	ID	*/
        public static int ID = 13;
        /** Display Type 14	Text	*/
        public static int Text = 14;
        /** Display Ty 15	Date	*/
        public static int Date = 15;
        /** Display Type 16	DateTime	*/
        public static int DateTime = 16;
        /** Display Type 17	List	*/
        public static int List = 17;
        /** Display Type 18	Table	*/
        public static int Table = 18;
        /** Display Type 19	TableDir	*/
        public static int TableDir = 19;
        /** Display Type 20	YN	*/
        public static int YesNo = 20;
        /** Display Type 21	Location	*/
        public static int Location = 21;
        /** Display Type 22	Number	*/
        public static int Number = 22;
        /** Display Type 23	BLOB	*/
        public static int Binary = 23;
        /** Display Type 24	Time	*/
        public static int Time = 24;
        /** Display Type 25	Account	*/
        public static int Account = 25;
        /** Display Type 26	RowID	*/
        public static int RowID = 26;
        /** Display Type 27	Color   */
        public static int Color = 27;
        /** Display Type 28	Button	*/
        public static int Button = 28;
        /** Display Type 29	Quantity	*/
        public static int Quantity = 29;
        /** Display Type 30	Search	*/
        public static int Search = 30;
        /** Display Type 31	Locator	*/
        public static int Locator = 31;
        /** Display Type 32 Image	*/
        public static int Image = 32;
        /** Display Type 33 Assignment	*/
        public static int Assignment = 33;
        /** Display Type 34	Memo	*/
        public static int Memo = 34;
        /** Display Type 35	PAttribute	*/
        public static int PAttribute = 35;
        /** Display Type 36	CLOB	*/
        public static int TextLong = 36;
        /** Display Type 37	CostPrice	*/
        public static int CostPrice = 37;
        /** Display Type 36	File Path	*/
        public static int FilePath = 38;
        /** Display Type 39 File Name	*/
        public static int FileName = 39;
        /** Display Type 40	URL	*/
        public static int URL = 40;
        /** Display Type 42	PrinterName	*/
        public static int PrinterName = 42;

        /**New  Display Type 44 Label */
        public static int Label = 44;
        #endregion

        /// <summary>
        ///Returns true if (numeric) ID (Table, Search, Account, ..).
        /// </summary>
        /// <param name="displayType"></param>
        /// <returns></returns>
        public static bool IsID(int displayType)
        {
            if (displayType == ID || displayType == Table || displayType == TableDir
                || displayType == Search || displayType == Location || displayType == Locator
                || displayType == Account || displayType == Assignment || displayType == PAttribute
                || displayType == Image || displayType == Color)
                return true;
            return false;
        }	//	isID

        /// <summary>
        ///Returns true, if DisplayType is numeric (Amount, Number, Quantity, Integer).
        /// </summary>
        /// <param name="displayType"></param>
        /// <returns></returns>
        public static bool IsNumeric(int displayType)
        {
            if (displayType == Amount || displayType == Number || displayType == CostPrice
                || displayType == Integer || displayType == Quantity)
                return true;
            return false;
        }	//	isNumeric

        /// <summary>
        ///	Get Default Precision.
        /// 	Used for databases who cannot handle dynamic number precision.
        /// </summary>
        /// <param name="displayType"></param>
        /// <returns></returns>
        public static int GetDefaultPrecision(int displayType)
        {
            if (displayType == Amount)
                return 2;
            if (displayType == Number)
                return 6;
            if (displayType == CostPrice
                || displayType == Quantity)
                return 4;
            return 0;
        }	//	getDefaultPrecision

        /// <summary>
        /// Returns true, if DisplayType is text (String, Text, TextLong, Memo).
        /// </summary>
        /// <param name="displayType"></param>
        /// <returns></returns>
        public static bool IsText(int displayType)
        {
            if (displayType == String || displayType == Text
                || displayType == TextLong || displayType == Memo
                || displayType == FilePath || displayType == FileName
                || displayType == URL || displayType == PrinterName)
                return true;
            return false;
        }	//	isText

        /// <summary>
        ///Returns truem if DisplayType is a Date.
        /// </summary>
        /// <param name="displayType"></param>
        /// <returns></returns>
        public static bool IsDate(int displayType)
        {
            if (displayType == Date || displayType == DateTime || displayType == Time)
                return true;
            return false;
        }	//	isDate

        /// <summary>
        ///Returns true if DisplayType is a VLookup (List, Table, TableDir, Search).
        /// </summary>
        /// <param name="displayType"></param>
        /// <returns></returns>
        public static bool IsLookup(int displayType)
        {
            if (displayType == List || displayType == Table
                || displayType == TableDir || displayType == Search)
                return true;
            return false;
        }	//	isLookup

        /// <summary>
        /// return True if display type is clientlook up(vlookup or locator) 
        /// </summary>
        /// <param name="displayType"></param>
        /// <returns></returns>
        public static bool IsClientLookup(int displayType)
        {
            //locator also a lookup in gwt
            return IsLookup(displayType) || displayType == FieldType.Locator;
        }

        /// <summary>
        ///Returns true if DisplayType is a Large Object
        /// </summary>
        /// <param name="displayType"></param>
        /// <returns></returns>
        public static bool IsLOB(int displayType)
        {
            if (displayType == Binary
                || displayType == TextLong)
                return true;
            return false;
        }	//	isLOB

        /// <summary>
        /// Is TextArea
        /// </summary>
        /// <param name="displayType"></param>
        /// <returns></returns>
        public static bool IsTextArea(int displayType)
        {
            return displayType == Text || displayType == Memo || displayType == TextLong;
        }

        /// <summary>
        /// Returns true if the field should be searched with case sensitivity
        /// </summary>
        /// <param name="displayType"></param>
        /// <returns></returns>
        public static bool IsCaseSensitive(int displayType)
        {
            return !IsText(displayType);
        }

        ///<summary>
        ///Get SQL DataType
        ///<param name="displayType">AD_Reference_ID</param>
        ///<param name="columnName">name</param>
        ///<param name="fieldLength">length</param>
        /// </summary>
        public static string GetSQLDataType(int displayType, String columnName, int fieldLength)
        {
            if (columnName.Equals("EntityType")
                || columnName.Equals("AD_Language")
                || columnName.Equals("DocBaseType"))
                return "VARCHAR2(" + fieldLength + ")";
            //	ID
            if (DisplayType.IsID(displayType))
            {
                if (displayType == DisplayType.Image 	//	FIXTHIS
                    && columnName.Equals("BinaryData"))
                    return "BLOB";
                //	ID, CreatedBy/UpdatedBy, Acct
                else if (columnName.EndsWith("_ID")
                    || columnName.EndsWith("tedBy")
                    || columnName.EndsWith("_Acct"))
                    return "NUMBER(10)";
                else if (fieldLength < 4)
                    return "CHAR(" + fieldLength + ")";
                else	//	EntityType, AD_Language	fallback
                    return "VARCHAR2(" + fieldLength + ")";
            }
            //
            if (displayType == DisplayType.Integer)
                return "NUMBER(10)";
            if (DisplayType.IsDate(displayType))
                return "DATE";
            if (DisplayType.IsNumeric(displayType))
                return "NUMBER";
            if (displayType == DisplayType.Binary)
                return "BLOB";
            if (displayType == DisplayType.TextLong
                || (displayType == DisplayType.Text && fieldLength >= 4000))
                return "CLOB";
            if (displayType == DisplayType.YesNo)
                return "CHAR(1)";
            if (displayType == DisplayType.List)
                return "CHAR(" + fieldLength + ")";
            if (displayType == DisplayType.Color)
            {
                if (columnName.EndsWith("_ID"))
                    return "NUMBER(10)";
                else
                    return "CHAR(" + fieldLength + ")";
            }
            if (displayType == DisplayType.Button)
            {
                if (columnName.EndsWith("_ID"))
                    return "NUMBER(10)";
                else
                    return "CHAR(" + fieldLength + ")";
            }

            if (displayType == DisplayType.Label)
            {
                if (columnName.EndsWith("_ID"))
                    return "NUMBER(10)";
                else
                    return "NVARCHAR2(" + fieldLength + ")";
            }


            if (!DisplayType.IsText(displayType))
            {
                //   s_log.severe("Unhandled Data Type = " + displayType);
            }
            return "NVARCHAR2(" + fieldLength + ")";
        }	//	getSQLDataType

        /// <summary>
        /// Get Sysytem Data Type against Display type value
        /// </summary>
        /// <param name="displayType"></param>
        /// <param name="yesNoAsBoolean"></param>
        /// <returns></returns>
        public static Type GetClass(int displayType, bool yesNoAsBoolean)
        {
            if (IsText(displayType) || displayType == List)
                return typeof(System.String);
            else if (IsID(displayType) || displayType == Integer)    //  note that Integer is stored as BD
                return typeof(System.Int32);
            else if (IsNumeric(displayType))
                return typeof(decimal);
            else if (IsDate(displayType))
                return typeof(System.DateTime);
            else if (displayType == YesNo)
                return yesNoAsBoolean ? typeof(System.Boolean) : typeof(System.String);
            else if (displayType == Button)
                return typeof(System.String);
            else if (IsLOB(displayType))	//	CLOB is String
                return typeof(System.Byte[]);
            //
            return typeof(System.Object);
        }   //  getClass

    }	//	FieldType

    /*************************************************************************************
     * 
     * Display Type class
     * 
     * **********************************************************************************/
    public class DisplayType : FieldType
    {
        //  See DBA_DisplayType.sql ----------------------------------------------

        /** Maximum number of digits    */
        private static int MAX_DIGITS = 28;        //  Oracle Standard Limitation 38 digits
        /** Digits of an Integer        */
        private static int INTEGER_DIGITS = 10;
        /** Maximum number of fractions */
        private static int MAX_FRACTION = 12;
        /** Default Amount Precision    */
        private static int AMOUNT_FRACTION = 2;

        /// <summary>
        ///   Return Format for numeric DisplayType	
        /// </summary>
        /// 
        /// <param name="displayType">Display Type (default Number)</param>
        /// <param name="language">Language</param>
        /// <returns>number format</returns>
        public static Format GetNumberFormat(int displayType, string language)
        {
            //Language myLanguage = language;
            //if (myLanguage == null)
            //    myLanguage = Language.getLoginLanguage();
            //Locale locale = myLanguage.getLocale();
            Format format = new Format();
            //if (locale != null)
            //    format = (DecimalFormat)NumberFormat.getNumberInstance(locale);
            //else
            //    format = (DecimalFormat)NumberFormat.getNumberInstance(Locale.US);
            //
            if (displayType == Integer)
            {
                //format.setParseIntegerOnly(true);
                format.MaxIntDigit = INTEGER_DIGITS;
                format.MaxFractionDigit = 0;
            }
            else if (displayType == Quantity)
            {
                format.MaxIntDigit = MAX_DIGITS;
                format.MaxFractionDigit = MAX_FRACTION;
            }
            else if (displayType == Amount)
            {
                format.MaxIntDigit = MAX_DIGITS;
                format.MaxFractionDigit = AMOUNT_FRACTION;
                format.MinFractionDigit = AMOUNT_FRACTION;
            }
            else if (displayType == CostPrice)
            {
                format.MaxIntDigit = MAX_DIGITS;
                format.MaxFractionDigit = MAX_FRACTION;
                format.MinFractionDigit = AMOUNT_FRACTION;
            }
            else //	if (displayType == Number)
            {
                format.MaxIntDigit = MAX_DIGITS;
                format.MaxFractionDigit = MAX_FRACTION;
                format.MinFractionDigit = 1;
            }
            return format;
        }	//	getDecimalFormat


        /// <summary>
        ///Return Format for numeric DisplayType
        /// </summary>
        /// <param name="displayType">Display Type</param>
        /// <returns>number format</returns>
        public static Format GetNumberFormat(int displayType)
        {
            return GetNumberFormat(displayType, null);
        }

        public static SimpleDateFormat GetDateFormat(int displayTye)
        {
            return new SimpleDateFormat(displayTye); 
        }
    }


    public class SimpleDateFormat
    {

        private Dictionary<int, String> _dateTimeFormats;

        public const int DATEFULL = -1;
        public const int DATEMEDIUM = -2;
        public const int DATESHORT = -3;

        private int _displayType = DisplayType.Date;

        //"(d) Short date: . . . . . . . {0:d}\n" +
        //       "(D) Long date:. . . . . . . . {0:D}\n" +
        //       "(t) Short time: . . . . . . . {0:t}\n" +
        //       "(T) Long time:. . . . . . . . {0:T}\n" +
        //       "(f) Full date/short time: . . {0:f}\n" +
        //       "(F) Full date/long time:. . . {0:F}\n" +
        //       "(g) General date/short time:. {0:g}\n" +
        //       "(G) General date/long time: . {0:G}\n" +
        //       "    (default):. . . . . . . . {0} (default = 'G')\n" +
        //       "(M) Month:. . . . . . . . . . {0:M}\n" +
        //       "(R) RFC1123:. . . . . . . . . {0:R}\n" +
        //       "(s) Sortable: . . . . . . . . {0:s}\n" +
        //       "(u) Universal sortable: . . . {0:u} (invariant)\n" +
        //       "(U) Universal full: . . . . . {0:U}\n" +
        //       "(Y) Year: . . . . . . . . . . {0:Y}\n",




        private string _dateFormatString = "";

        public SimpleDateFormat()
        {
            _dateTimeFormats = new Dictionary<int, string>();
            _dateTimeFormats.Add(DisplayType.Date, "{0:d}");
            _dateTimeFormats.Add(DisplayType.DateTime, "{0:G}");
            _dateTimeFormats.Add(DisplayType.Time, "{0:T}");
            _dateTimeFormats.Add(-1, "{0:F}");//not used 
            _dateTimeFormats.Add(-2, "{0:D}");//not used 
            _dateTimeFormats.Add(-3, "{0:t}");//* reserve for future use
        }

        /// <summary>
        /// constructor
        /// </summary>
        /// <param name="displayType"></param>
        public SimpleDateFormat(int displayType):this()
        {
            _displayType = displayType; 
        }



        /// <summary>
        /// return format string
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public String Format(object obj)
        {
            DateTime dt;
            if(obj is DateTime )
            {
                dt = (DateTime)obj;
            }
            else if(obj is long)
            {
                dt =  System.DateTime.Now  ;// CommonFunctions.CovertMilliToDate((long)obj);
            }
            else
            {
                throw new ArgumentException("Input is not in correct format(long/datetime)");
            }
            string fmtStr = _dateTimeFormats[_displayType];

            try
            {
                return String.Format(System.Globalization.CultureInfo.InvariantCulture,fmtStr, dt);
            }
            catch(Exception e)
            {
                //Logging.VLogger.Get().Log(VAdvantage.Logging.Level.SEVERE, e.Message);
                return "";
            }
        }
    }



    /*********************************************************************************
     * 
     *   MultiMap List
     * 
     *********************************************************************************/
    /// <summary>
    /// MultiMap allows multiple keys with their values.
    ///   It accepts null values as keys and values.
    ///   (implemented as two generic  lists)
    /// </summary>
    /// <typeparam name="K"></typeparam>
    /// <typeparam name="V"></typeparam>

    public class MultiMap<K, V>
    {
        /// <summary>
        ///Constructor 
        /// </summary>
        public MultiMap()
        {
            m_keys = new List<K>();
            m_values = new List<V>();
        }   //  MultiMap

        /// <summary>
        ///Constructor
        /// </summary>
        /// <param name="initialCapacity"></param>
        public MultiMap(int initialCapacity)
        {
            //m_keys = new List<K>();
            //m_values = new List<V>();
        }   //  MultiMap

        private List<K> m_keys = null;
        private List<V> m_values = null;

        /// <summary>
        /// Return number of elements
        /// </summary>
        /// <returns></returns>
        public int Count()
        {
            return m_keys.Count;
        }   //  size

        /// <summary>
        ///Is Empty
        /// </summary>
        /// <returns></returns>
        public bool IsEmpty()
        {
            return (m_keys.Count == 0);
        }   //  isEmpty

        /// <summary>
        ///Contains Key
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool ContainsKey(K key)
        {
            return m_keys.Contains(key);
        }   //  containsKey

        /// <summary>
        /// Contains Value
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool ContainsValue(V value)
        {
            return m_values.Contains(value);
        }   //  containsKey

        /// <summary>
        ///Return ArrayList of Values of Key
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public List<V> Get(K key)
        {
            return GetValues(key);
        }   //  get

        /// <summary>
        /// Return ArrayList of Values of Key
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public List<V> GetValues(K key)
        {
            List<V> list = new List<V>();
            //  We don't have it
            if (!m_keys.Contains(key))
                return list;
            //  go through keys
            int size = m_keys.Count;
            for (int i = 0; i < size; i++)
            {
                if (m_keys[i].Equals(key))
                    if (!list.Contains(m_values[i]))
                        list.Insert(list.Count, m_values[i]);
            }
            return list;
        }   //  getValues

        /// <summary>
        /// Return ArrayList of Keys with Value
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public List<K> GetKeys(V value)
        {
            List<K> list = new List<K>();
            //  We don't have it
            if (!m_values.Contains(value))
                return list;
            //  go through keys
            int size = m_values.Count;
            for (int i = 0; i < size; i++)
            {
                if (m_values[i].Equals(value))
                    if (!list.Contains(m_keys[i]))
                        list.Insert(list.Count, m_keys[i]);
            }
            return list;
        }

        /// <summary>
        /// Put Key & Value
        /// </summary>
        /// <param name="key">Key Of Record</param>
        /// <param name="value">Value OfRecord</param>
        /// <returns></returns>
        public void Add(K key, V value)
        {
            m_keys.Add(key);
            m_values.Add(value);
            //return null;
        }   //  put

        public void Insert(K key, V value)
        {
            m_keys.Insert(m_keys.Count, key);
            m_values.Insert(m_values.Count, value);
            //return null;
        }   //  put


        public void Clear()
        {
            m_keys.Clear();
            m_values.Clear();
        }   //  clear

        /// <summary>
        ///  Return HashSet of Keys
        /// </summary>
        /// <returns></returns>
        public HashSet<K> KeySet()
        {
            HashSet<K> keys = new HashSet<K>(m_keys);
            return keys;
        }   //  keySet

        /// <summary>
        /// Return Collection of values
        /// </summary>
        /// <returns></returns>
        public List<V> Values()
        {
            return m_values;
        }	//	values

        /// <summary>
        /// Returns class name and number of entries
        /// </summary>
        /// <returns></returns>
        public override String ToString()
        {
            return "MultiMap #" + m_keys.Count;
        }

    }   //  MultiMap


    public class MessageFormat
    {

        public MessageFormat(string ptrn)
            : this()
        {
            ApplyPattern(ptrn);

        }
        //"(C) Currency: . . . . . . . . {0:C}\n" +
        //"(D) Decimal:. . . . . . . . . {0:D}\n" +
        //"(E) Scientific: . . . . . . . {1:E}\n" +
        //"(F) Fixed point:. . . . . . . {1:F}\n" +
        //"(G) General:. . . . . . . . . {0:G}\n" +
        //"    (default):. . . . . . . . {0} (default = 'G')\n" +
        //"(N) Number: . . . . . . . . . {0:N}\n" +
        //"(P) Percent:. . . . . . . . . {1:P}\n" +
        //"(R) Round-trip: . . . . . . . {1:R}\n" +
        //"(X) Hexadecimal:. . . . . . . {0:X}\n",
        private Dictionary<string, string> allFormats = new Dictionary<string, string>(15);
        private String[] typeList = { "", "", "number", "", "date", "", "time", "", "choice" };
        private String[] modifierList = { "", "", "currency", "", "percent", "", "integer" };
        private String[] dateModifierList = { "", "", "short", "", "medium", "", "long", "", "full" };

        private string pattern = "";

        public MessageFormat()
        {
            allFormats.Add("currency", "C");
            allFormats.Add("decimal", "D");
            allFormats.Add("general", "G");
            allFormats.Add("number", "N");
            allFormats.Add("percent", "P");
            allFormats.Add("shortdate", "d");
            allFormats.Add("longdate", "D");
            allFormats.Add("shorttime", "t");
            allFormats.Add("longtime", "T");
            allFormats.Add("fulltime", "T");
            allFormats.Add("fulldate", "D");
            allFormats.Add("mediumdate", "d");
            allFormats.Add("mediumtime", "t");
            allFormats.Add("choice", "");
        }


        /// <summary>
        /// return fromarted value
        /// </summary>
        /// <param name="arguments"></param>
        /// <returns></returns>
        public string Format(object[] arguments)
        {
            try
            {
                return String.Format(System.Globalization.CultureInfo.InvariantCulture, this.pattern, arguments);
            }
            catch (FormatException e)
            {
               // Logging.VLogger.Get().Log(VAdvantage.Logging.Level.WARNING, e.Message);
                return "";
            }
            catch (Exception e)
            {
               // Logging.VLogger.Get().Log(VAdvantage.Logging.Level.WARNING, e.Message);
                return "";
            }
        }


        public void ApplyPattern(String pattern)
        {
            if (!CmpreFormat(pattern))
            {
                this.pattern = pattern;
                return;
            }

            List<string> segmentsList = new List<string>();

            StringBuilder segment = new StringBuilder("");
            for (int i = 0; i < pattern.Length; ++i)
            {
                char ch = pattern[i];
                if (ch == '{')
                {
                    if (segment.Length == 0)
                    {
                        segment.Append(ch);
                    }
                    else
                    {
                        segmentsList.Add(segment.ToString());
                        segment.Length = 0;
                        segment.Append(ch);
                    }
                }
                else if (ch == '}')
                {
                    segment.Append(ch);
                    segmentsList.Add(segment.ToString());
                    segment.Length = 0;
                }
                else if (i == pattern.Length)
                {
                    segmentsList.Add(segment.ToString());
                    segment.Length = 0;
                }
                else
                {
                    segment.Append(ch);
                }
            }


            this.pattern = ParsePattren(segmentsList);
        }

        private string ParsePattren(List<string> segments)
        {
            StringBuilder result = new StringBuilder(" ");
            for (int i = 0; i < segments.Count; i++)
            {
                string part = segments[i];
                if (part.StartsWith("{") && CmpreFormat(part))
                {
                    part = GetFormat(part.Split(','));
                    result.Append(part);
                    continue;
                }
                result.Append(part);
            }
            return result.ToString();
        }


        private string GetFormat(string[] segments)
        {
            StringBuilder format = new StringBuilder(segments[0]).Append(":");
            string newFormat = "";
            switch (FindKeyword(segments[1], typeList))
            {
                case 0:
                    break;
                case 1:
                case 2:// number
                    switch (FindKeyword(segments[2].ToString(), modifierList))
                    {
                        case 0: // default;
                            newFormat = allFormats["number"];
                            break;
                        case 1:
                        case 2:// currency
                            newFormat = allFormats["currency"];
                            break;
                        case 3:
                        case 4:// percent
                            newFormat = allFormats["percent"];
                            break;
                        case 5:
                        case 6:// integer
                            newFormat = allFormats["decimal"];
                            break;
                        default: // pattern
                            newFormat = allFormats["number"];
                            break;
                    }
                    break;
                case 3:
                case 4: // date
                    switch (FindKeyword(segments[2], dateModifierList))
                    {
                        case 0: // default
                            newFormat = allFormats["shortdate"];
                            break;
                        case 1:
                        case 2: // short
                            newFormat = allFormats["shortdate"];
                            break;
                        case 3:
                        case 4: // medium
                            newFormat = allFormats["mediumdate"];
                            break;
                        case 5:
                        case 6: // long
                            newFormat = allFormats["longdate"];
                            break;
                        case 7:
                        case 8: // full
                            newFormat = allFormats["fulldate"];
                            break;
                        default:
                            newFormat = segments[3].ToString();
                            break;
                    }
                    break;
                case 5:
                case 6:// time
                    switch (FindKeyword(segments[2].ToString(), dateModifierList))
                    {
                        case 0: // default
                            newFormat = allFormats["shorttime"];
                            break;
                        case 1:
                        case 2: // short
                            newFormat = allFormats["shorttime"];
                            break;
                        case 3:
                        case 4: // medium
                            newFormat = allFormats["mediumtime"];
                            break;
                        case 5:
                        case 6: // long
                            newFormat = allFormats["mediumtime"];
                            break;
                        case 7:
                        case 8: // full
                            newFormat = allFormats["mediumtime"];
                            break;
                        default:
                            newFormat = segments[2].ToString();
                            break;
                    }
                    break;
                case 7:
                case 8:// choice
                    try
                    {
                        newFormat = segments[3];
                        allFormats["choice"] = segments[3].ToString();
                    }
                    catch (Exception e)
                    {
                        throw new ArgumentException(
                                                 "Choice Pattern incorrect");
                    }
                    break;
                default:
                    throw new ArgumentException("unknown format type at ");
            }
            segments = null;
            format.Append(newFormat).Append("}");
            return format.ToString();
        }




        /// <summary>
        /// is it Vienna format or not
        /// </summary>
        /// <param name="ptrn"></param>
        /// <returns></returns>
        private bool CmpreFormat(string ptrn)
        {
            if (ptrn.Contains("number,") || ptrn.Contains("date,") || ptrn.Contains("time,") || ptrn.Contains("custom,"))
            {
                return true;
            }
            return false;
        }

        private int FindKeyword(string text, string[] str)
        {
            for (int i = 0; i < str.Length; i++)
            {
                if (text.Equals(str.GetValue(i)))
                    return i;
            }
            return -1;
        }
    }
}